package cn.efunbox.afw.core.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
/**
 * 封装了一些采用HttpClient发送HTTP请求的方法
 * @desc 本工具所采用的是最新的HttpComponents-Client-4.2.1
 */
public class HttpClientUtil {
    private HttpClientUtil(){}
     
    private static Log logger = LogFactory.getLog(HttpClientUtil.class);
    public  static  final String HTTP_GET= "GET";
    public  static  final String HTTP_POST= "POST";


    /**
     * 发送HTTP_GET请求
     * @desc 该方法会自动关闭连接,释放资源
     * @param reqURL    请求地址(含参数)
     * @return 远程主机响应正文
     */
    public static String doGet(String reqURL){
        return sendRequestByNativeJava(HTTP_GET,reqURL, null);
    }

    /**
     /**
     * 发送HTTP_POST请求
     * @desc 该方法会自动关闭连接,释放资源
     * @param reqURL        请求地址
     * @return 远程主机响应正文
     */
    public static String doPost( String reqURL){
        return sendRequestByNativeJava(HTTP_POST,reqURL, null);
    }
    /**
     /**
     * 发送HTTP_POST请求
     * @desc 该方法会自动关闭连接,释放资源
     * @param reqURL        请求地址
     * @param params        请求参数
     * @return 远程主机响应正文
     */
    public static String doPost( String reqURL, Map<String, String> params){
        return sendRequestByNativeJava(HTTP_POST,reqURL, params);
    }

    /**
     * 发送HTTP_POST请求,json格式数据 效率低于 原生 Java HTTP
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    public static String doPostByJson(String url, String body) throws Exception {
        CloseableHttpClient httpclient = HttpClients.custom().build();
        HttpPost post = null;
        String resData = null;
        CloseableHttpResponse result = null;
        try {
            post = new HttpPost(url);
            HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
            post.setConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build());
            post.setHeader("Content-Type", "application/json");
            post.setEntity(entity2);
            result = httpclient.execute(post);
            if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) {
                resData = EntityUtils.toString(result.getEntity());
            }
        } finally {
            if (result != null) {
                result.close();
            }
            if (post != null) {
                post.releaseConnection();
            }
            httpclient.close();
        }
        return resData;
    }
    /**
     * 发送HTTP_POST请求,json格式数据 效率低于 原生 Java HTTP
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    public static byte[] doPostAndReturnBytesByJson(String url, String body) throws Exception {
        CloseableHttpClient httpclient = HttpClients.custom().build();
        HttpPost post = null;
        CloseableHttpResponse result = null;
        try {
            post = new HttpPost(url);
            HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
            post.setConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build());
            post.setHeader("Content-Type", "application/json");
            post.setEntity(entity2);
            result = httpclient.execute(post);
            if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) {
                if (result.getEntity() != null) {
                    InputStream instream = result.getEntity().getContent();
                    if (instream != null) {
                        long contentLength = result.getEntity().getContentLength();
                        if (contentLength > 2147483647L) {
                            throw new IOException("Content too large to be buffered: " + contentLength + " bytes");
                        }
                        int limit = 1048576;
                        if (contentLength == -1L || contentLength > (long)limit) {
                            logger.warn("Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.");
                        }
                        logger.debug("Buffering response body");
                        ByteArrayOutputStream outstream = new ByteArrayOutputStream(contentLength > 0L ? (int)contentLength : 4096);
                        byte[] buffer = new byte[4096];

                        int len;
                        while((len = instream.read(buffer)) > 0) {
                            outstream.write(buffer, 0, len);
                        }
                        outstream.close();
                        return  outstream.toByteArray();
                    }
                }
            }
        }catch (IOException e){
            logger.error("网络请求失败 msg={}",e);
            throw new IOException("网络请求失败 url="+url);
        }finally {
            if (result != null) {
                result.close();
            }
            if (post != null) {
                post.releaseConnection();
            }
            httpclient.close();
        }
        return null;
    }

    /**
     * https posp请求，可以绕过证书校验
     * @param url
     * @param params
     * @return
     */
    public static final String postSSLRequest(String url, Map<String, String> params) {
		String responseContent = null;
		HttpClient httpClient = new DefaultHttpClient();
		//创建TrustManager
		X509TrustManager xtm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		//这个好像是HOST验证
		X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
			public boolean verify(String arg0, SSLSession arg1) {
				return true;
			}
			public void verify(String arg0, SSLSocket arg1) throws IOException {}
			public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
			public void verify(String arg0, X509Certificate arg1) throws SSLException {}
		};
		try {
			//TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
			SSLContext ctx = SSLContext.getInstance("TLS");
			//使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
			ctx.init(null, new TrustManager[] { xtm }, null);
			//创建SSLSocketFactory
			SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
			socketFactory.setHostnameVerifier(hostnameVerifier);
			//通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
			httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
            if (null!=params) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
			httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity(); // 获取响应实体
			if (entity != null) {
				responseContent = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			httpClient.getConnectionManager().shutdown();
		}
		return responseContent;
	}
    /**
     * 发送HTTP_POST请求
     * @desc 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
     * @desc 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
     * @param reqURL 请求地址
     * @param params 发送到远程主机的正文数据,其数据类型为<code>java.util.Map<String, String></code>
     * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
     */
    public static String sendRequestByNativeJava(String method, String reqURL, Map<String, String> params){
        StringBuilder sendData = new StringBuilder();
        if (null!=params) {
            for(Map.Entry<String, String> entry : params.entrySet()){
                sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        if(sendData.length() > 0){
            sendData.setLength(sendData.length() - 1); //删除最后一个&符号
        }
        HttpURLConnection httpURLConnection = null;
        OutputStream out = null; //写
        InputStream in = null;   //读
        int httpStatusCode = 0;  //远程主机响应的HTTP状态码
        try{
            URL sendUrl = new URL(reqURL);
            httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
            httpURLConnection.setRequestMethod(method);
            httpURLConnection.setDoOutput(true);        //指示应用程序要将数据写入URL连接,其值默认为false
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(30000); //30秒连接超时
            httpURLConnection.setReadTimeout(30000);    //30秒读取超时

            out = httpURLConnection.getOutputStream();
            out.write(sendData.toString().getBytes());

            //清空缓冲区,发送数据
            out.flush();

            //获取HTTP状态码
            httpStatusCode = httpURLConnection.getResponseCode();

            in = httpURLConnection.getInputStream();
            byte[] byteDatas = new byte[in.available()];
            in.read(byteDatas);
            return new String(byteDatas);
        }catch(Exception e){
            logger.debug(e.getMessage());
            return "Failed`" + httpStatusCode;
        }finally{
            if(out != null){
                try{
                    out.close();
                }catch (Exception e){
                    logger.debug("关闭输出流时发生异常,堆栈信息如下", e);
                }
            }
            if(in != null){
                try{
                    in.close();
                }catch(Exception e){
                    logger.debug("关闭输入流时发生异常,堆栈信息如下", e);
                }
            }
            if(httpURLConnection != null){
                httpURLConnection.disconnect();
                httpURLConnection = null;
            }
        }
    }


    public static void main(String[] args) throws  Exception{

        String url="https://www.jd.com";
        Long start=System.currentTimeMillis();
        for (int i=0;i<1;i++){
            System.out.println(new String(HttpClientUtil.doPostAndReturnBytesByJson(url,"{}")));
            //logger.info();
        }
        System.out.println("耗时: "+(System.currentTimeMillis()-start)+" 毫秒 ");

       /* Long start1=System.currentTimeMillis();
        for (int i=0;i<5;i++){
           // HttpClientUtil.doPost(url,null);
            logger.info(  HttpClientUtil.doPost(url,null));
        }
        logger.info("耗时: "+(System.currentTimeMillis()-start1)+" 毫秒 ");

        Long start2=System.currentTimeMillis();
        for (int i=0;i<5;i++){
            HttpClientUtil.postSSLRequest(url,null);
            //logger.info();
        }
        logger.info("耗时: "+(System.currentTimeMillis()-start2)+" 毫秒 ");*/

    }
}





















/* *//**
 * 发送HTTP_GET请求
 * @desc 该方法会自动关闭连接,释放资源
 * @param reqURL    请求地址(含参数)
 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
 * @return 远程主机响应正文
 *//*
    static String getRequest(String reqURL, String decodeCharset){
        long responseLength = 0;       //响应长度
        String responseContent = null; //响应内容
        HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
        HttpGet httpGet = new HttpGet(reqURL);           //创建org.apache.http.client.methods.HttpGet
        try{
            HttpResponse response = httpClient.execute(httpGet); //执行GET请求
            HttpEntity entity = response.getEntity();            //获取响应实体
            if(null != entity){
                responseLength = entity.getContentLength();
                responseContent = EntityUtils.toString(entity, null==decodeCharset ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity); //Consume response content
            }
            logger.debug("请求地址: " + httpGet.getURI());
            logger.debug("响应状态: " + response.getStatusLine());
            logger.debug("响应长度: " + responseLength);
            logger.debug("响应内容: " + responseContent);
        }catch(ClientProtocolException e){
            logger.debug("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
        }catch(ParseException e){
        	logger.debug(e.getMessage(), e);
        }catch(IOException e){
        	logger.debug("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
        }
        return responseContent;
    }*/
